package ru.spb.osll.myfit.chart;

import org.apache.log4j.Logger;
import ru.spb.osll.myfit.fixtures.base.OneLineFixture;
import ru.spb.osll.myfit.server.chart.ChartsBuilder;
import ru.spb.osll.myfit.server.chart.ChartsBuilderLoader;
import ru.spb.osll.myfit.server.chart.JarChartsBuilderLoader;
import ru.spb.osll.myfit.util.MyFitProperties;
import util.GracefulNamer;

import java.io.File;
import java.io.IOException;

/**
 * User: Artem Bukhonov
 * Email: nerzhulart@gmail.com
 */

public class DrawChartsFixture extends OneLineFixture {
  private static final String CHART_BUILDER_SUFFIX = "ChartsBuilder";
  private ChartsBuilderLoader m_chartsBuilderLoader;
  private Logger log = Logger.getLogger(DrawChartsFixture.class);

  public DrawChartsFixture() {
    try {
      m_chartsBuilderLoader = new JarChartsBuilderLoader(MyFitProperties.getTestDirectory() + File.separator + "fixtures");
    } catch (IOException e) {
      log.error("Can't create ChartsBuilderLoader", e);
    }
  }

  public boolean drawCharts(String prefix) throws ClassNotFoundException, InstantiationException, IllegalAccessException, IOException {
    if (m_chartsBuilderLoader == null) {
      String message = "Charts builder loader was not created";
      log.error(message);
      throw new IllegalStateException(message);
    }
    String disgracedPrefix = GracefulNamer.disgrace(prefix);
    String chartBuilderClassName = disgracedPrefix + CHART_BUILDER_SUFFIX;
    try {
      ChartsBuilder chartsBuilder = m_chartsBuilderLoader.getChartsBuilderInstanceByName(chartBuilderClassName);
      chartsBuilder.doDrawCharts();
    } catch (ClassNotFoundException e) {
      String message = "Charts builder class corresponding to \"" + prefix + "\"(" + chartBuilderClassName + ") not found";
      log.error(message, e);
      throw new ClassNotFoundException(message, e);
    } catch (InstantiationException e) {
      String message = "Unable to instantiate class " + disgracedPrefix;
      log.error(message, e);
      throw new InstantiationException(message);
    }
    if (m_chartsBuilderLoader instanceof JarChartsBuilderLoader) {
      ((JarChartsBuilderLoader) m_chartsBuilderLoader).close();
    }
    return true;
  }

  public static String[] getTestTableTemplates() {
    return new String[]{"|draw charts||"};
  }

}
